<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace app\http\middleware\api;

use app\Request;
use app\services\user\UserAuthServices;
use hdphp\interfaces\MiddlewareInterface;

/**
 * 客户身份验证中间件
 * Class ClientMiddleware
 * @package app\http\middleware\api
 */
class ClientMiddleware implements MiddlewareInterface
{

    public function handle(Request $request, \Closure $next)
    {
        $userId = trim(ltrim($request->param('userid')));

        if (!$userId) {
            return app('json')->fail('缺少Userid!');
        }

        try {
            /** @var UserAuthServices $service */
            $service = app()->make(UserAuthServices::class);
            $authInfo = $service->parseClient($userId);
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }

        $request->macro('clientInfo', function (string $key = null) use ($authInfo) {
            if ($key) {
                return $authInfo[$key] ?? null;
            } else {
                return $authInfo;
            }
        });

        $request->macro('userid', function () use ($userId) {
            return $userId;
        });


        return $next($request);
    }
}
